// @Author EthanScriptOn
// @Desc
package service

import (
	"fmt"
	"gitee.com/fatzeng/srf_switch_basic_components/switch_log"
	"gitee.com/fatzeng/srf_switch_dynamic_logic_director/dao"
	"gitee.com/fatzeng/srf_switch_dynamic_logic_director/dto"
	"gitee.com/fatzeng/srf_switch_dynamic_logic_director/middleware"
	"gitee.com/fatzeng/srf_switch_dynamic_logic_director/pojo"
	"gitee.com/fatzeng/srf_switch_dynamic_logic_director/request"
	"github.com/gin-gonic/gin"
	"time"
)

func PublishSwitch(ctx *gin.Context, param *request.SwitchContentRequest) (err error) {
	if param == nil || !param.IsValid() {
		return fmt.Errorf("param is invalid")
	}
	value, exists := ctx.Get(middleware.USER_INFO)
	if !exists {
		err = fmt.Errorf("user information not found")
		switch_log.Logger().Error("switch_service/PublishSwitch", err)
		return
	}

	information, ok := value.(*pojo.SrfSwitchUserInformation)
	if !ok {
		err = fmt.Errorf("user information type error")
		switch_log.Logger().Error("switch_service/PublishSwitch", err)
		return
	}

	switchBody := new(dto.SwitchBody)
	switchBody.SwitchRemark = param.SwitchContent
	switchBody.SwitchName = param.SwitchName
	switchBody.Env = param.Env
	switchBody.Group = param.Group
	switchBody.Namespace = param.Namespace
	switchBody.OperatorUserId = information.UserId
	switchBody.CreatedAt = time.Now()
	err = dao.SwitchPublish(switchBody)
	if err != nil {
		return fmt.Errorf("PublishSwitch error: %v", err)
	}
	return
}

func GetSwitchList(param *request.SwitchListRequest) (result *dto.SwitchList, err error) {
	if param == nil || !param.IsValid() {
		return nil, fmt.Errorf("param is invalid")
	}
	resultList, count, err := dao.SwitchRuleList(param)
	if err != nil {
		return nil, fmt.Errorf("get switch list error: %v", err)
	}
	return &dto.SwitchList{
		List:  resultList,
		Count: count,
	}, nil
}

func GetSwitchOptionDetail(param *request.SwitchOptionDetailRequest) (result *dto.SwitchDetailList, err error) {
	if param == nil || !param.IsValid() {
		return nil, fmt.Errorf("param is invalid")
	}
	resultList, count, err := dao.SwitchRuleDetailList(param)
	if err != nil {
		return nil, fmt.Errorf("get switch option detail list error: %v", err)
	}
	return &dto.SwitchDetailList{
		List:  resultList,
		Count: count,
	}, nil
}
